package com.lct.simpleforecast

import android.app.Activity
import android.content.Context
import java.util.*

/**
 * Author：SkySmile
 * Date：2018/7/16
 * Description：管理Activity的类
 */
class ActivityManager private constructor() {
    private val activityStack = Stack<Activity>()

    companion object {
        val instance = ActivityManager()
    }

    /**
     * 添加Activity到堆栈
     *
     * @param activity 要添加的Activity实例
     */
    fun addActivity(activity: Activity) {
        activityStack.add(activity)
    }

    /**
     * 移除指定的Activity
     *
     * @param activity 要移除的Activity实例
     */
    fun removeActivity(activity: Activity) {
        activityStack.remove(activity)
        activity.finish()
    }

    /**
     * 获取当前的Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): Activity {
        return activityStack.lastElement()
    }

    /**
     * 跳转到指定的已经打开的Activity
     *
     * @param cls Class
     */
    fun <T> returnToActivity(cls: Class<T>) {
        kotlin.run breaking@{
            activityStack.forEach {
                if (activityStack.peek().javaClass == cls) {
                    return@breaking
                } else {
                    activityStack.peek().finish()
                }
            }
        }
    }

    /**
     * 退出应用
     *
     * @param context 上下文
     * @param isBackground 是否有后台程序运行
     */
    fun appExit(context: Context, isBackground: Boolean) {
        try {
            activityStack.forEach {
                it.finish()
            }
            activityStack.clear()
            val manager = context.getSystemService(Context.ACTIVITY_SERVICE)
                    as android.app.ActivityManager
            manager.killBackgroundProcesses(context.packageName)
        } catch (e: Exception) {

        } finally {
            if (!isBackground) {
                System.exit(0)
            }
        }
    }
}